using Services;
using UnityEngine;
using UnityEngine.UI;

public class HPBar : MonoBehaviour
{
    private ActionController actionController;

    private Character character;
    private float fillAmount;
    private Image bar;
    private Text text;
    private LinearTransformation linear_bar;

    private void Awake()
    {
        actionController = ServiceLocator.Get<ActionController>();
        bar = GetComponentInParent<Image>();
        text = GetComponent<Text>();
        linear_bar = new LinearTransformation();
        linear_bar.Tick += SetFillAmount;
    }

    public void OnEnable()
    {
        character = GetComponentInParent<Character>();
        if (character != null)
        {
            character.HPChange += OnHPChange;
            text.text = $"{character.HealthPoint}/{character.data.maxHP}";
        }
    }

    private void OnHPChange(float current, float max, float _)
    {
        text.text = $"{current}/{max}";
        fillAmount = current / max;
        if (fillAmount != bar.fillAmount)
            linear_bar.Initialize(bar.fillAmount, fillAmount, 0.5f);
        if (actionController.displayTime < 0.5f)
            actionController.displayTime += 0.5f;
    }

    private void SetFillAmount(float value)
    {
        bar.fillAmount = value;
    }
}
